package beanstao.util.io;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class StringOutputStream extends OutputStream
{

	private final StringBuilder sb;
	private ByteArrayOutputStream baos;
	private final String charset;

	public StringOutputStream(StringBuilder sb)
	{
		this(sb, null);
	}

	public StringOutputStream(StringBuilder sb, String charset)
	{
		this.sb = sb;
		this.baos = new ByteArrayOutputStream();
		this.charset = charset;
	}

	/**
	 * 完成本方法后,确认字符串已经完成写入后,务必调用flash方法!
	 */
	@Override
	public void write(int b) throws IOException
	{
		if (null == this.baos)
		{
			throw new IOException("Stream is closed");
		}
		this.baos.write(b);
	}

	/**
	 * 使用StringBuilder前,务必调用
	 */
	@Override
	public void flush() throws IOException
	{
		super.flush();
		this.baos.flush();
		if (this.baos.size() > 0)
		{
			if (this.charset == null)
			{
				this.sb.append(new String(this.baos.toByteArray()));
			}
			else
			{
				this.sb.append(new String(this.baos.toByteArray(), this.charset));
			}
			this.baos.reset();
		}
	}

	@Override
	public void close() throws IOException
	{
		this.flush();
		this.baos = null;
	}

	public StringBuilder getStringBuilder()
	{
		return this.sb;
	}

}
